<!--企业角色管理 companyRoleManager-->
<template>
  <Layout>
    <Form ref="form1" :model="dataToQuery" :label-width="120">
      <Row v-show="!switchFlag" class="query-form">
        <Col span="8">
          <FormItem label="企业名称：" prop="order">
            <cascader-dom class="query-form-el" ref='queryOrgCascader' @setOrgInfo='setQueryCompanyName' :orgTree="true"
                          :setCurrentName="{label:dataToQuery.companyName,value:dataToQuery.companyId}"></cascader-dom>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="变更后姓名：" >
            <Input  class=''  type='text' v-model='dataToQuery.userName'></Input>
          </FormItem>
        </Col>

        <Col span="8" >
          <Button @click="reset" class="ivu-btn-reset">重置</Button>
          <Button type="primary" class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
        </Col>
      </Row>
      <Row class="query-form">
        <Col span="24">
          <Button size="large" class="ivu-btn-add" icon="md-add" @click="addInfo1('add')">管理员新增</Button>
          <Button size="large" class="ivu-btn-add" icon="md-add" @click="addInfo1('edit')">管理员变更</Button>
          <Button size="large" class="ivu-btn-add" icon="md-add" @click="addInfo1('del')">管理员删除</Button>
        </Col>
      </Row>
    </Form>
    <Table ref='table' :height="tableHeight" no-data-text="没有查询到相关数据!" @on-selection-change='getSelectRows'
           :loading='pageStatus.loading'
           border :columns="columns1" :data="dataTable">
    </Table>
    <Row style="margin-right:10px;">
      <Col span="24">
        <Page style="float: right" :total="pagedata.total" :page-size="pagedata.pageSize" @on-change="pageChange"
              @on-page-size-change="pageSizeChange" :page-size-opts="pageSizeArray" show-total show-sizer
              show-elevator/>
      </Col>
    </Row>

    <user-manager-select @closeModel="closeModel" v-if="userForSelectModal"
                         :multiple="true"
                         :company-id="dataToView.companyId"
                         :userForSelectModal="userForSelectModal"
                         :model="true" @getSelectModelData="getSelectModelData"/>

    <Modal title="企业系统管理员" :transfer=false footer-hide v-model="userForSelectModalBefore" :width=900 @on-cancel="closeModel">
      <company-role-manager @closeModel="closeModel" v-if="userForSelectModalBefore"
                           :company-id="dataToView.companyId"
                            :selectModal="userForSelectModalBefore"
                            @getSelectModelData="getSelectModelDataBefore"/>
    </Modal>

    <Modal :title="this.getModalTitle(title)" :transfer=false :mask-closable="false" v-model="dialogShow" v-if="dataToView && dialogShow"  :width=800  class-name='limit-height-dialog'>
      <Row>
        <Col span="24">
          <Form ref="dialogForm" :class="mode === 'view'?'modal-view-detail':''" :show-message="false" :model="dataToView" :rules="mode === 'view'?{}:ruleCustom" :label-width="mode === 'view'?160:null" :label-position="mode === 'view'?'right':'top'">
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label='企业名称：' prop='companyId'>
                  <div v-if="mode === 'view'">{{dataToView.companyName}}</div>
                  <!--<Input v-else class='query-form-el' type='text' readonly v-model='dataToView.companyName'></Input>-->
                  <cascader-dom v-else class='query-form-el' ref='orgCascader' @setOrgInfo='setCompanyId' @setOrgname="setCompanyName" :orgTree="true"
                                 :currentOrgId="dataToView.companyId" :rootOrgId="dataToView.belongOrgId"
                                 :setCurrentName="{label:dataToView.companyName,value:dataToView.companyId}" ></cascader-dom>
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label='管理员类型：' prop='adminType'>
                  <div v-if="mode === 'view'">{{ dataToView.adminTypeDesc }}</div>
                  <Select v-else v-model='dataToView.adminType' placeholder="请选择管理员类型" @on-change="adminTypeChange" class='query-form-el'>
                    <Option value="SA">安全</Option>
                    <Option value="EN">环保</Option>
                    <Option value="EN_SA">安全与环保</Option>
                  </Select>
                </FormItem>
              </Col>
            </Row>
            <Row v-if="dataToView.applyType!=='edit'" type="flex" justify="space-around" class="code-row-bg">
              <Col span="11" v-if="dataToView.applyType==='del'">
                <FormItem label='删除的管理员：' prop='adminUserIdBefore'>
                  <div v-if="mode === 'view'">{{ dataToView.adminUserIdBeforeName }}</div>
                  <div v-else>
                    <Input class='query-form-el' placeholder="请选择管理员" type='text'
                           v-model='dataToView.adminUserIdBeforeName' @on-focus="userForSelectModalBefore=true" readonly suffix="ios-search"></Input>
                  </div>
                </FormItem>
              </Col>
              <Col span="11" v-else>
                <FormItem label='管理员姓名：' prop='adminUserId'>
                  <div v-if="mode === 'view'">{{ dataToView.adminUserName }}</div>
                  <div v-else>
                    <Input class='query-form-el' placeholder="请选择管理员" type='text'
                           v-model='dataToView.adminUserName' @on-focus="userForSelectModal=true" readonly  suffix="ios-search"></Input>
                  </div>
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label='审批人：' prop='applyUserId'>
                  <div v-if="mode === 'view'">{{ dataToView.applyUserName }}</div>
                  <!--<Input v-else class='query-form-el' placeholder="请填写填报人" type='text' readonly v-model='dataToView.applyUserName'></Input>-->
                  <div v-else>
                    <Select v-if="show" v-model='dataToView.applyUserId' placeholder="请选择审批人" class='query-form-el'>
                      <Option v-for="item in dictMap[this.dataToView.companyId]" :value="item.userId" :disabled="item.disabled" :label="item.userName" :key="item.userId">
                        <span>{{item.userName }}</span>
                        <span style="float:right;color:#ccc">{{item.userType }}</span>
                      </Option>
                    </Select>
                  </div>
                </FormItem>
              </Col>
            </Row>

            <Row v-if="dataToView.applyType==='edit'" type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label='变更前姓名：' prop='adminUserIdBefore'>
                  <div v-if="mode === 'view'">{{ dataToView.adminUserIdBeforeName }}</div>
                  <div v-else>
                    <Input class='query-form-el' placeholder="请选择管理员" type='text'
                           v-model='dataToView.adminUserIdBeforeName' @on-focus="userForSelectModalBefore=true" readonly suffix="ios-search"></Input>
                  </div>
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label='变更后姓名：' prop='adminUserId'>
                  <div v-if="mode === 'view'">{{ dataToView.adminUserName }}</div>
                  <div v-else>
                    <Input class='query-form-el' placeholder="请选择管理员" type='text'
                           v-model='dataToView.adminUserName' @on-focus="userForSelectModal=true" readonly  suffix="ios-search"></Input>
                  </div>
                </FormItem>
              </Col>
            </Row>
            <Row v-if="dataToView.applyType==='edit'" type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label='审批人：' prop='applyUserId'>
                  <div v-if="mode === 'view'">{{ dataToView.applyUserName }}</div>
                  <div v-else>
                    <Select v-if="show" v-model='dataToView.applyUserId' placeholder="请选择审批人" class='query-form-el'>
                      <Option v-for="item in dictMap[this.dataToView.companyId]" :value="item.userId" :disabled="item.disabled" :label="item.userName" :key="item.userId">
                        <span>{{item.userName }}</span>
                        <span style="float:right;color:#ccc">{{item.userType }}</span>
                      </Option>
                    </Select>
                  </div>
                </FormItem>
              </Col>
              <Col span="11"></Col>
            </Row>

            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label='申请人：' prop='createUserName'>
                  <div v-if="mode === 'view'">{{ dataToView.createUserName }}</div>
                  <Input v-else class='query-form-el' placeholder="请填写填报人" type='text' readonly
                         v-model='dataToView.createUserName'></Input>
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label='填报时间：' prop='createDate'>
                  <div v-if="mode === 'view'">{{ renderViewDate(dataToView.createDate) }}</div>
                  <DatePicker v-else class="query-form-el" placeholder="请选择填报时间" readonly
                              v-model='dataToView.createDate'></DatePicker>
                </FormItem>
              </Col>
			  <Col span="23">
			  <Alert type="error">若审批人有误，请在综合工作-企业信息中更新安全或环保负责人信息。</Alert>
			  </Col>
            </Row>
          </Form>
        </Col>
      </Row>
      <div slot="footer">
        <Button v-if="mode != 'view'" type="primary"  class='ivu-btn-save' @click="submit('dialogForm')" >确定</Button>
        <Button v-if="mode != 'view'" type="primary"  class='ivu-btn-cancel' @click="handleCancel" >取消</Button>
        <Button v-if="mode === 'view'" class='ivu-btn-save' @click="dialogShow=false">关闭</Button>
      </div>
    </Modal>
    <Modal :transfer=false v-model="model4"  :width=900>
      <Tabs>
        <TabPane label="历史记录">
          <Table ref='table1' border :columns="columns2" no-data-text="没有查询到相关数据！" style="margin-top: 0" :loading="loading2"
                 :data="history" width="100%"  :height="450" highlight-row stripe size="small"></Table>
        </TabPane>
        <TabPane label="流程图">
          <div style="height: 450px; overflow-y: auto; overflow-x: auto">
            <img :src="imgUrl" >
          </div>
        </TabPane>
      </Tabs>
      <div slot="footer">
        <Button @click="model4=false" class="ivu-btn-save">关闭</Button>
      </div>
    </Modal>
  </Layout>
</template>

<script>
import {Api} from '@/api/index.js'
import userManagerSelect from "./userManagerSelect";
import companyRoleManager from './companyRoleManager'
import pageCommonFunction from '@/components/pageCommonFunction.js'
import {sessionStorage} from "@/common/cacheUtils";

var cascaderDom = () => import('@/components/cascader-dom.vue');

export default {
  components: {
    cascaderDom,userManagerSelect,companyRoleManager
  },
  data() {
    return {
      ...this.createCommonDataField(),
        userForSelectModalBefore:false,
      userForSelectModal:false,
      columns1: [
        {title: '序号', width: 70, fixed: 'left', align: 'center', render: this.indexColumnsRender},
          {
              title: '状态',
              align: 'center',
              fixed:'left',
              key: 'status',
              width: 100,
              render: (h, params) => {
                  let color = 'green';
                  if (params.row.procinstState == undefined || params.row.procinstState == null || params.row.procinstState == 2) {
                      color = 'red';
                  }
                  if (params.row.procinstState == 1) {
                      color = 'blue';
                  }
                  return h('div', [
                      h('span', {
                          style: {
                              color: color
                          }
                      }, params.row.procinstState == 1 ? '审批中' : params.row.procinstState == 2 ? '审批不通过' : params.row.procinstState == 3 ? '审批通过' : '未上报' || '--')
                  ]);
              }
          },
          {key: 'applyType', title: '申请类型', align: 'center', minWidth: 100,
              render: (h, params) => {
                  return h('span',  params.row.applyType ==='add' ? '添加' : params.row.applyType === 'edit' ? '修改' : params.row.applyType === 'del' ? '删除' : '')

              }},
          {key: 'adminTypeDesc', title: '管理员类型', align: 'center', minWidth: 100},
         {key: 'adminUserName', title: '管理员姓名', align: 'center', minWidth: 100},
          {key: 'adminUserIdBeforeName', title: '变更前姓名', align: 'center', minWidth: 100},
          {key: 'createUserName', title: '申请人', align: 'center', minWidth: 100},
          {key: 'applyTime',  title: '申请时间', align: 'center', minWidth: 100,render:this.renderCellDate},
          {key: 'companyName', title: '所属单位', align: 'center', minWidth: 180},
        {key: 'belongOrgName', title: '所属二级集团', align: 'center', minWidth: 180},
          {
              title: '操作',
              key: 'action',
              fixed: 'right',
              width: 280,
              align: 'center',
              render: (h, params) => {
                      let flag = this.currentUser.loginId === this.Common.admin || this.currentUser.userId === params.row.createUserId || this.currentUser.userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') != undefined || this.currentUser.userBeHandedOver.find(obj => obj == params.row.createUserId) != undefined
                      return h('div', [
                      h('A', {
                          props: {
                              type: 'primary',
                              size: 'small'
                          },
                          style: {
                              fontSize: '14px',

                          },
                          on: {
                              click: () => {
                                  this.viewData(params);
                              }
                          }
                      }, '详情'),
                      h('Divider', {
                          props: {
                              type: 'vertical',
                          }
                      }, ''),
                      h('A', {
                          props: {
                              type: 'primary',
                              size: 'small'
                          },
                          style: {
                              fontSize: '14px',
                              color: params.row.procinstState == "1" || params.row.procinstState == "2" || params.row.procinstState == "3" ? '#d0d0d0':flag ? '':'#d0d0d0',
                              pointerEvents: params.row.procinstState == "1" || params.row.procinstState == "2" || params.row.procinstState == "3" ? 'none' :  flag ? '' : 'none'
                          },
                          on: {
                              click: () => {
                                  this.editData(params);
                              }
                          }
                      }, '修改'), h('Divider', {
                          props: {
                              type: 'vertical',
                          }
                      }, ''),
                      h('A', {
                          props: {
                              type: 'primary',
                              size: 'small'
                          },
                          style: {
                              fontSize: '14px',
                              color:  params.row.procinstState == "1" || params.row.procinstState == "2" || params.row.procinstState == "3" ? '#d0d0d0': flag ? '':'#d0d0d0',
                              pointerEvents: params.row.procinstState == "1" || params.row.procinstState == "2" || params.row.procinstState == "3" ? 'none' :  flag? '' : 'none'
                          },
                          on: {
                              click: () => {
                                  this.$Modal.confirm({
                                      title: '提示',
                                      content: '<p>是否要提交？</p>',
                                      onOk: () =>{
                                          this.reportInfo(params.row);
                                      } ,
                                      onCancel: () => {
                                      }
                                  });
                              }
                          }
                      }, '上报'),
                      h('Divider', {
                          props: {
                              type: 'vertical',
                          }
                      }, ''),
                      h('A', {
                          props: {
                              type: 'error',
                              size: 'small'
                          },
                          style: {
                              fontSize: '14px',
                              color:  params.row.procinstState == "1" || params.row.procinstState == "2" || params.row.procinstState == "3" ? '#d0d0d0': flag ? 'red':'#d0d0d0',
                              pointerEvents: params.row.procinstState == "1" || params.row.procinstState == "2" || params.row.procinstState == "3" ? 'none' : flag ? '' : 'none'
                          },
                          on: {
                              click: () => {
                                  this.deleteData(params);
                              }
                          }
                      }, '删除'),
                      h('Divider', {
                          props: {
                              type: 'vertical',
                          }
                      }, ''),
                      h('a', {
                          props: {
                              type: 'primary',
                          },
                          style: {
                              fontSize: '14px',
                              color: params.row.procinstId == null ? '#d0d0d0' : '',
                              pointerEvents: params.row.procinstId == null ? 'none' : ''
                          },
                          on: {
                              click: () => {
                                  this.imgUrl = Api.getFlowImg + '/' + params.row.procinstId
                                  this.showHistory(params.row);
                              }
                          }
                      },'审批记录')
                  ]);
              }
          }
      ],
        ruleCustom: {
            adminType: [ { required: true, message: '请选择管理员类型', trigger: 'change',}],
            adminUserId: [ { required: true, message: '请选择管理员姓名', trigger: 'change',}],
            applyUserId: [ { required: true, message: '审批人不能为空', trigger: 'change',}],
            adminUserIdBefore: [ { required: true, message: '请选择更改后姓名', trigger: 'change',}],
        },
      currentUser:sessionStorage('userId').getObject('userId'),
      tableHeight: 10,
      dictMap: {},
      // api
      queryUrl: Api.queryRoleUserApply,
      deleteUrl: Api.deleteRoleUserApply,
      updateUrl: Api.updateRoleUserApply,
      saveUrl: Api.saveRoleUserApply,
        show:true,
        title:'',
        applyType:'',

        imgUrl:'',
        history:[],
        model4:false,
        loading2:false,
        columns2: [
            {type: 'index', title: '序号', width: 80, align: 'center',},
            {width: 180, title: '审批时间', key: 'endTime', align: 'center',},
            {width: 185, title: '节点名称', key: 'name', align: 'center',},
            {width: 120, title: '审批人', key: 'userName', align: 'center'},
            {width: 100, title: '审批意见', key: 'route', align: 'center'},
            {width: 200, title: '备注', key: 'opinions', align: 'center'},
        ],
    }
  },
  async mounted() {
    this.setTableHeight();
    this.query();
  },
  methods: {
    ...pageCommonFunction,

      reportInfo(row) {
          let user = sessionStorage('userId').getObject('userId')
          this.loading = true;
          let data = {
              key: "roleManagerUserApply",
              createUserId: user.userId,
              userName: user.userName,
              workId: row.id,
              type:"roleManagerUserApply",
              formKey: "roleManagerUserApproval",
              user1: row.applyUserId,
          };
          this.$http.post(Api.submit, data).then(function (res) {
              this.loading = false;
              this.$Message.success({
                  content: '上报成功',
                  duration: 4
              });
              this.query();
          }, function (err) {
              this.loading = false;
              this.$Message.error({
                  content: '上报失败',
                  duration: 4
              });
          });
      },
      showHistory(row) {
          this.model4 = true;
          this.loading2 = true;
          this.$http.get(Api.getHistory + '/' + row.procinstId, {params: {}}).then((res) => {
              this.history = res.data;
              this.loading2 = false;
          }).catch(e => {
              this.$Message.error("数据获取失败")
          })
      },
      adminTypeChange(val){
          // this.dataToView.applyUserId = null
          this.show =false
          let arr = this.dictMap.applyUsers===this.dataToView.companyId ? undefined: this.dictMap[this.dataToView.companyId]
          if (!arr) {
              this.$http.get(Api.getEnvInfoCompanByCompanyId+ this.dataToView.companyId).then((res) => {
                  if (res.data.status === 200) {
                      if (res.data.data.enPerson === res.data.data.saPerson) {
                          arr = [
                              {userId:res.data.data.enPerson,userName:res.data.data.enPersonName,userType:'安全环保负责人',disabled:false},
                          ]
                      } else {
                          arr = [
                              {userId:res.data.data.enPerson,userName:res.data.data.enPersonName,userType:'环保部门负责人',disabled:val.indexOf('EN')===-1},
                              {userId:res.data.data.saPerson,userName:res.data.data.saPersonName,userType:'安全部门负责人',disabled:val.indexOf('SA')===-1}
                          ]
                      }
                      this.dictMap[this.dataToView.companyId] = arr
                      this.$nextTick(()=>{
                          this.dictMap.applyUsers = undefined
                          this.show =true
                      })
                  }else{
                      this.$Message.error("当前公司没有在企业信息内维护");
                  }
              }).catch(e => {
                  this.$Message.error("当前公司没有在企业信息内维护");
              })
          }else {
              this.dictMap[this.dataToView.companyId].forEach(item => {
                  if (item.userType === '环保部门负责人') {
                      item['disabled'] = val.indexOf('EN')===-1
                  } else if (item.userType === '安全部门负责人') {
                      item['disabled'] = val.indexOf('SA')===-1
                  }
              })
              this.$nextTick(()=>{
                  this.show =true
              })
          }
      },
    deleteData(params) {
      this.deleteDateAjax(params);
    },
      addInfo1(type){
          this.applyType = type
          // if (type === 'del') {
          //     this.adminTypeChange('EN_SA')
          // }
          this.title = type==='add'?'管理员新增':type==='edit'?'管理员替换':type==='del'?'管理员删除':''
          this.addInfo()
      },
      async beforeEditDialogOpen(data) {
          if (!this.dictMap[data.row.companyId]) {
              this.dictMap.applyUsers = data.row.companyId
              this.dictMap[data.row.companyId] = [{
                  userId:data.row.applyUserId,
                  userName:data.row.applyUserName
              }]
          }
      },
    query() {
        this.dataToQuery.type = 1
      this.queryAjax();
    },
    submit(name) {
        this.submitAjax(name)
    },
    getSelectModelData(data){
        this.$set(this.dataToView,'adminUserId',data.userId)
        this.$set(this.dataToView,'adminUserName',data.userName)
    },
      getSelectModelDataBefore(data){
          this.$set(this.dataToView,'adminUserIdBefore',data.userId)
          this.$set(this.dataToView,'adminUserIdBeforeName',data.userName)
      },
    closeModel(){
      this.userForSelectModal = false;
        this.userForSelectModalBefore = false;
    },

    handleCancel() {
      this.dataToView = {};
      this.dialogShow = false;
      this.query();
    },
    createEmptyDataToAdd() {
      return {
          applyType: this.applyType,
      }
    }
  },
  watch: {},
}
</script>

<style lang='css' scoped>
.rpt-form {
}

/deep/ .rpt-form .query-form-el {
  width: 100%;
}

/deep/ .rpt-form .ivu-form-item {
  margin-bottom: 24px;
}

</style>
